﻿using System;
using System.IO;
using System.Reflection;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using VietThinks.Model;
using IServiceProvider = VietThinks.Contract.IServiceProvider;
using System.Security;

[assembly: SecurityRules(SecurityRuleSet.Level1)]
namespace VietThinks.Service
{
    public class ServiceProvider : IServiceProvider
    {
        public readonly string DefaultWindsorConfigurationXmlFile;

        #region Singleton Representation

        static ServiceProvider()
        {
            Instance = new ServiceProvider();
        }

        public static ServiceProvider Instance { get; private set; }

        private ServiceProvider()
        {
            string assemblyUriLocation = Assembly.GetExecutingAssembly().CodeBase;
            string assemblyLocation = new Uri(assemblyUriLocation).LocalPath;
            DefaultWindsorConfigurationXmlFile = Path.Combine(
                Path.GetDirectoryName(assemblyLocation),
                "VietThinks.Service.Windsor.xml");

            this.container = new WindsorContainer(new XmlInterpreter(DefaultWindsorConfigurationXmlFile));

            RuleConfigurer.Configure();
        }

        #endregion

        private readonly IWindsorContainer container;

        #region IServiceProvider Members

        public TService GetService<TService>()
            where TService : class
        {
            return this.container.GetService<TService>();
        }

        public object GetService(System.Type serviceType)
        {
            return this.container.GetService(serviceType);
        }

        #endregion
    }
}
